package com.fernfx.xingtan.main.ui;

import android.content.Intent;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.fernfx.xingtan.Constant;
import com.fernfx.xingtan.R;
import com.fernfx.xingtan.common.base.BaseFragment;
import com.fernfx.xingtan.contacts.ui.AddFriendsActivity;
import com.fernfx.xingtan.contacts.ui.NewFriendsActivity;
import com.fernfx.xingtan.contacts.ui.UserDetailsActivity;
import com.fernfx.xingtan.main.adapter.SortAdapter;
import com.fernfx.xingtan.main.contract.ContactsInfoContract;
import com.fernfx.xingtan.main.entity.ContactsInfoEntity;
import com.fernfx.xingtan.main.entity.PersonEntity;
import com.fernfx.xingtan.main.presenter.ContactsInfoPresenter;
import com.fernfx.xingtan.utils.CollectionUtil;
import com.fernfx.xingtan.utils.PinyinComparatorUtil;
import com.fernfx.xingtan.view.bar.SideBar;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnItemClick;

/**
 * 联系人
 */

public class ContactsInfoFragment extends BaseFragment implements ContactsInfoContract.View, SideBar.OnTouchingLetterChangedListener,
        ListView.OnItemClickListener,View.OnClickListener,View.OnTouchListener {

    @BindView(R.id.contacts_info_sbar)
    SideBar sidebar;
    @BindView(R.id.contacts_info_liv)
    ListView contactsInfoLiv;
    @BindView(R.id.select_dialog_tv)
    TextView selectDialogTv;
    @BindView(R.id.search_edit)
    EditText searchEdit;

    //init presenter
    private ContactsInfoContract.Presenter presenter = null;
    private SortAdapter sortadapter;

    //通讯录联系人信息
    public ArrayList<ContactsInfoEntity.ObjBean.RecordsBean> contactsInfoList = null;
    //init personEntityList
    private List<PersonEntity> personEntityList = null;

    public static final int OPERATION_CONTACTS_STATUS = 19;

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_contacts_info;
    }

    @Override
    public BaseFragment getFragment() {
        return this;
    }

    public void loadContactsInfo() {
        requestArgsMap = Constant.RequestArgs.REQUEST_ARGS_MAP;
        requestArgsMap.clear();
        requestArgsMap.put("pageNo", Constant.ApplicationVariable.PAGE_NO);
        requestArgsMap.put("pageSize", Constant.ApplicationVariable.PAGE_SIZE);
        requestArgsMap.put("orderBy", "add_time");
        requestArgsMap.put("order", "desc");
        presenter.loadContactsInfo(requestArgsMap);
    }

    @Override
    protected void initView() {
        presenter = new ContactsInfoPresenter();
        presenter.init(this);
        //设置弹出的dialog
        sidebar.setTextView(selectDialogTv);
    }

    @Override
    protected void initData() {
        personEntityList = new ArrayList<>(4);
        contactsInfoList = new ArrayList<>(10);

        loadContactsInfo();
    }

    @Override
    protected void initListener() {
        sidebar.setOnTouchingLetterChangedListener(this);
        searchEdit.setOnTouchListener(this);
    }

    @Override
    public void onTouchingLetterChanged(String s) {
        // 该字母首次出现的位置
        if (null == sortadapter) {
            return;
        }
        int position = sortadapter.getPositionForSelection(s.charAt(0));

        if (position != -1) {
            contactsInfoLiv.setSelection(position);
        }
    }

    @OnItemClick({R.id.contacts_info_liv})
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position >= 0 && position <= contactsInfoList.size()) {
            //get item
            ContactsInfoEntity.ObjBean.RecordsBean recordsBean = contactsInfoList.get(position);
            //check bean
            recordsBean = (null == recordsBean ? new ContactsInfoEntity.ObjBean.RecordsBean() : recordsBean);
            //跳转到详情页面
            UserDetailsActivity.start(getActivity(),recordsBean);
        }
    }

    @OnClick({R.id.append_friend_tv})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.append_friend_tv:
                NewFriendsActivity.start(this);
                break;
        }
    }

    @Override
    public void showContactsInfo(){
        final String[] nameArrays = getNames(contactsInfoList);
        personEntityList = presenter.getContactsInfoList(nameArrays);
        // 数据在放在adapter之前需要排序
        Collections.sort(presenter.getContactsInfoList(nameArrays), new PinyinComparatorUtil());
        //刷新adapter
        refurbishContacts();
    }

    /*
     *刷新通讯录
     */
    public void refurbishContacts(){
        //设置adapter
        sortadapter = new SortAdapter(getActivity(), personEntityList,contactsInfoList);
        contactsInfoLiv.setAdapter(sortadapter);
    }

    /*
     *获得显示联系人名称
     */
    private String[] getNames(List<ContactsInfoEntity.ObjBean.RecordsBean> contactsInfoList) {
        String[] names = new String[contactsInfoList.size()];
        for (int i = 0; i < names.length; i++) {
            final ContactsInfoEntity.ObjBean.RecordsBean recordsBean = contactsInfoList.get(i);
            String name = recordsBean.getNickname();
            if (TextUtils.isEmpty(name)) {
                continue;
            }
            names[i] = name;
        }
        return names;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (!CollectionUtil.isEmpty(contactsInfoList)) {
            contactsInfoList.clear();
            contactsInfoList = null;
        }
        if (!CollectionUtil.isEmpty(personEntityList)) {
            personEntityList.clear();
            personEntityList = null;
        }
        if (null != sortadapter) {
            sortadapter = null;
        }
        if (null != presenter) {
            presenter.detachView();
            presenter = null;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (OPERATION_CONTACTS_STATUS == requestCode)  {
            loadContactsInfo();
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (v.getId()) {
            case R.id.search_edit:
                if (AddFriendsActivity.isStartFlag) {
                    AddFriendsActivity.start(getActivity());
                }
                break;
        }
        return false;
    }
}
